import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  ManyToOne,
  OneToMany,
  JoinColumn,
  Unique,
  CreateDateColumn,
  UpdateDateColumn,
  OneToOne,
} from 'typeorm';

import { User, PunchFood, Point } from '@/modules/app/entities';
import { ApiHideProperty } from '@nestjs/swagger';
import { IsEnum, IsNumber, IsOptional } from 'class-validator';

export enum MealType {
  /**
   * 早餐
   */
  BREAKFAST = 'BREAKFAST',
  /**
   * 午餐
   */
  LUNCH = 'LUNCH',
  /**
   * 晚餐
   */
  DINNER = 'DINNER',
  /**
   * 加餐
   */
  SNACK = 'SNACK',
}

@Entity('punch')
// 只会在新建表或新建索引时，根据你实体的字段生成唯一索引，如果更换这个，同步就会报错
// 他是删除原有索引再去加新的索引，但是又无法删除，导致报错，需要手动去删除外键
@Unique(['userId', 'mealType', 'punchDate'])
export class Punch {
  @PrimaryGeneratedColumn('increment')
  punchId: number;

  @IsNumber()
  @Column()
  userId: number;

  @ApiHideProperty()
  @ManyToOne(() => User, (user) => user.punch)
  @JoinColumn({ name: 'userId' })
  user: User;

  /**
   * 进餐类型
   * BREAKFAST: 早餐
   * LUNCH: 午餐
   * DINNER: 晚餐
   * SNACK: 加餐
   */
  @IsEnum(MealType)
  @Column({
    type: 'enum',
    enum: MealType,
  })
  mealType: MealType;

  // 多对多，多个punch可以有多个food
  @OneToMany(() => PunchFood, (punchFood) => punchFood.punch, {
    cascade: true, // 级联操作
    onDelete: 'CASCADE',
  })
  punchFood: PunchFood[];

  /**
   * 日期
   * @example 2025-10-01
   */
  @Column()
  punchDate?: string;

  /**
   * 积分ID
   */
  @Column({
    nullable: true,
  })
  @IsOptional()
  pointId?: number;

  /**
   * 积分
   */
  @OneToOne(() => Point, { eager: true })
  @JoinColumn({ name: 'pointId' })
  point: Point;

  @CreateDateColumn()
  createdAt?: Date;

  @UpdateDateColumn()
  updatedAt?: Date;
}
